package com.situ.ymall.admin.intercepter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.ymall.admin.entity.APIResult;
import com.situ.ymall.admin.entity.Root;
import com.situ.ymall.admin.service.RootService;
import com.situ.ymall.admin.util.TokenUtil;
import com.situ.ymall.admin.util.TokenUtil.Token;

/*Intercepter Filter
 *
 */
@Component	//组件
public class RootIntercepter implements HandlerInterceptor{
		@Autowired
		private RootService rootService;
		
		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
				throws Exception {
			//如果用户没有登陆，拦截
			//1.获取客户端传递来的token字符串
			String strToken = request.getHeader("token");
			if (strToken == null || strToken.length() ==0) {
				//用户没有登陆
				setResponse(response,"用户未登录，请登录后操作！！");
				//拦截
				return false;
			}
			//2.解密token，时间有没有过期
			Token token = TokenUtil.parseToken(strToken);
			if (token.getStatus() == 1) {
				setResponse(response, "登陆已过期，请重新登陆");
				return false;
			}
			//3.是不是一个有效的用户	
			String rootName = token.getCode();
			Root root = rootService.getByRootName(rootName);
			if (root == null) {
				setResponse(response, "当前用户无效");
				return false;
			}
			
			//4 禁用
			if (root.getStatus() == 1) {
				setResponse(response, "用户已被禁用,请联系管理员");
				return false;
			}
			
			//5 刷新token,重置有效时间
			strToken = TokenUtil.createToken(token.getCode());
			response.setHeader("token", strToken);
			
			return true; //放行
		}
	
		private void setResponse(HttpServletResponse response,String msg) throws IOException {
			APIResult apiResult = APIResult.unauthorized(msg);
			//将APiResult封装成JSON格式的字符串
			ObjectMapper mapper = new ObjectMapper();
			String json = mapper.writeValueAsString(apiResult);
			//由Response
			response.setContentType("application/json;charset=utf-8"); 
			response.getWriter().write(json);
		} 
	
}
